package zhuoer.adv2;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Arrays;
import java.util.Scanner;

public class PictureVerify {

	public static void main(String[] args) throws IOException {
		Scanner sc = new Scanner(System.in);
		System.out.print("请输入文件名：");
		String filePath = sc.nextLine();
		File f = new File(filePath);
		String fileName = f.getName();
		// 获得文件的后缀
		String houzhui = fileName.substring(fileName.lastIndexOf('.') + 1)
				.toUpperCase();

		FileInputStream fin = new FileInputStream(f);
		int ar[] = new int[8];
		for (int i = 0; i < ar.length; i++)
			ar[i] = fin.read();
		fin.close();

		switch (houzhui) {
		case "JPG":
			if (ar[0] == 0xFF && ar[1] == 0xD8) {
				System.out.println("这是jpg文件");
			} else {
				System.out.println("不是jpg");
			}
			break;
		case "GIF":
			int[] a2 = Arrays.copyOf(ar, 6);
			boolean b1 = Arrays.equals(a2, new int[] { 0x47, 0x49, 0x46, 0x38,
					0x39, 0x61 });
			boolean b2 = Arrays.equals(a2, new int[] { 0x47, 0x49, 0x46, 0x38,
					0x37, 0x61 });
			if (b1 || b2) {
				System.out.println("这是gif格式");
			} else {
				System.out.println("不是gif");
			}

			break;
		case "PNG":
			boolean b3 = Arrays.equals(ar, new int[] { 0X89, 0X50, 0X4E, 0X47,
					0X0D, 0X0A, 0X1A, 0X0A });
			if (b3) {
				System.out.println("合法的png");
			} else {
				System.out.println("非法的png");
			}
			break;
		default:
			System.out.println("文件类型和后缀不搭！");
			break;
		}
	}
}
